package com.wyh.yuhcloud.exception;


import com.wyh.yuhcloud.core.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 统一系统异常处理
     * @param e 异常
     * @param request 请求
     * @param response 响应
     * @return 结果集
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    @ResponseBody
    public Result exception(Exception e, HttpServletRequest request, HttpServletResponse response){
        log.error("{}",e.getMessage());
        return new Result(10000,"未知系统异常");
    }

    /**
     * 对方法异常进行处理
     * @param e 异常
     * @param request 请求
     * @param response 响应
     * @return 结果集
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Result exception(MethodArgumentNotValidException e, HttpServletRequest request, HttpServletResponse response){
        log.info("MethodArgumentNotValidException 异常\t{}",e.getMessage());
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String message = "参数校验异常";
        if (!errors.isEmpty()){
            message = errors.get(0).getDefaultMessage();
        }
        return new Result(10010,message);
    }



    @ExceptionHandler({LoginFeignException.class})
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    @ResponseBody
    public Result exception(LoginFeignException e, HttpServletRequest request, HttpServletResponse response){
        log.info("FeignException 异常\t{}",e.getMessage());
        return new Result(10000,e.getMessage());
    }

/*    @ExceptionHandler({BadCredentialsException.class})
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    @ResponseBody
    public Result exception(BadCredentialsException e, HttpServletRequest request, HttpServletResponse response){
        log.info("FeignException 异常\t{}",e.getMessage());
        return new Result(11000,e.getMessage());
    }*/
}
